<?php

/**
 * ECSHOP 首页文件
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');



if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);

$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile)/i";

if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
{
    $Loaction = 'mobile/';

    if (!empty($Loaction))
    {
        ecs_header("Location: $Loaction\n");

        exit;
    }

}


/*------------------------------------------------------ */
//-- Shopex系统地址转换
/*------------------------------------------------------ */
if (!empty($_GET['gOo']))
{
    if (!empty($_GET['gcat']))
    {
        /* 商品分类。*/
        $Loaction = 'category.php?id=' . $_GET['gcat'];
    }
    elseif (!empty($_GET['acat']))
    {
        /* 文章分类。*/
        $Loaction = 'article_cat.php?id=' . $_GET['acat'];
    }
    elseif (!empty($_GET['goodsid']))
    {
        /* 商品详情。*/
        $Loaction = 'goods.php?id=' . $_GET['goodsid'];
    }
    elseif (!empty($_GET['articleid']))
    {
        /* 文章详情。*/
        $Loaction = 'article.php?id=' . $_GET['articleid'];
    }

    if (!empty($Loaction))
    {
        ecs_header("Location: $Loaction\n");

        exit;
    }
}

//判断是否有ajax请求
$act = !empty($_GET['act']) ? $_GET['act'] : '';
if ($act == 'cat_rec')
{
    $rec_array = array(1 => 'best', 2 => 'new', 3 => 'hot');
    $rec_type = !empty($_REQUEST['rec_type']) ? intval($_REQUEST['rec_type']) : '1';
    $cat_id = !empty($_REQUEST['cid']) ? intval($_REQUEST['cid']) : '0';
    include_once('includes/cls_json.php');
    $json = new JSON;
    $result   = array('error' => 0, 'content' => '', 'type' => $rec_type, 'cat_id' => $cat_id);

    $children = get_children($cat_id);
    $smarty->assign($rec_array[$rec_type] . '_goods',      get_category_recommend_goods($rec_array[$rec_type], $children));    // 推荐商品
    $smarty->assign('cat_rec_sign', 1);
    $result['content'] = $smarty->fetch('library/recommend_' . $rec_array[$rec_type] . '.lbi');
    die($json->encode($result));
}

if ($act =='send_sms')
{
	$result=array('error'=>1,'content'=>'发送成功','sms_token'=>'');
	 
	
	$type = $_REQUEST['type'];
	$phone = $_REQUEST['phone'];
	$captcha = $_REQUEST['captcha'];
	$sms_token = $_REQUEST['sms_token'];
	$kkkey = "123454536f667445454d537973576562";//32位随机数字
	$kkiv = "1234577290ABCDEF";//16位随机数
	$key = urldecode($_REQUEST['key']);
	
	
	if($phone=='')
	{
		$result['content']='手机不能为空';
		showmsg_with_token($result);
	}
	if(!preg_match('/^1[13578]\d{9}$/', $phone))
	{
		$result['content']='手机格式不正确';
		showmsg_with_token($result);
	}
	
	$pattern = '1234567890';
	$rand = '';
	for($i = 0; $i < 6; $i++) {
		$rand .= $pattern {mt_rand ( 0, 9 )}; //生成php随机数
	}
	switch ($type)
	{
		case 'reg':
			//内容加密
			$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$kkkey,$phone,MCRYPT_MODE_CBC,$kkiv));
			
			//两个匹配是否相等
			if(strcmp($encrypted, $key)!= 0)
			{
				$result['content']='数据异常';
				showmsg_with_token($result);
			}
			
			if ($sms_token != $_SESSION['sms_token']){
				$result['content'] = '非法操作';
				showmsg_with_token($result);
			}
			
			if (empty($captcha)){
				$result['content'] = '请输入图形验证码';
				showmsg_with_token($result);
			}
			
			/* 检查验证码 */
			include_once('includes/cls_captcha.php');
			
			$validator = new captcha();
			if (!$validator->check_word($captcha))
			{
				$result['content'] = '图形验证码错误';
				showmsg_with_token($result);
			}
			
			if ($user->check_phone($phone)){
				$result['content'] = $user->error;
				showmsg_with_token($result);
			}
			
			$param = array('code'=>$rand);
			
			break;
		case 'edit':
			if ($user->check_phone($phone)){
				$result['content'] = $user->error;
				die(json_encode($result));
			}
			$param = array('code'=>$rand);
			break;
		default:
			$result['content'] = '参数错误';
			die(json_encode($result));
			break;
	}
	
	$tpl = get_sms_tpl($type);
	if (!$tpl){
		$result['content'] = "短信模板错误，请联系管理员。";
		showmsg_with_token($result);
	}
	$tpl_id = $tpl['tpl_id'];
	
	if (!update_sms_time($phone,$type,$rand)){
		$result['content'] = "手机号".$phone."每日限发3条验证短信";
		showmsg_with_token($result);
	}
	
	$result = send_sms($phone, $tpl_id, $param);
// 	$result['error'] = 0;
	showmsg_with_token($result);
}

if ($act =='get_sms_token')
{
	$result['error'] = 0;
	showmsg_with_token($result);
}

/*------------------------------------------------------ */
//-- 判断是否存在缓存，如果存在则调用缓存，反之读取相应内容
/*------------------------------------------------------ */
/* 缓存编号 */
$cache_id = sprintf('%X', crc32($_SESSION['user_rank'] . '-' . $_CFG['lang']));
if (strpos($_SERVER['REQUEST_URI'],'.php')!==false){
// 	jump_404();
}
if (!$smarty->is_cached('index.dwt', $cache_id))
{
    assign_template();
    $position = assign_ur_here('',$GLOBALS['_CFG']['shop_title']);
    $smarty->assign('page_title',      $position['title']);    // 页面标题
    $smarty->assign('ur_here',         $position['ur_here']);  // 当前位置


    /* meta information */
    $smarty->assign('keywords',        htmlspecialchars($_CFG['shop_keywords']));
    $smarty->assign('description',     htmlspecialchars($_CFG['shop_desc']));
    $smarty->assign('flash_theme',     $_CFG['flash_theme']);  // Flash轮播图片模板

    $smarty->assign('feed_url',        ($_CFG['rewrite'] == 1) ? 'feed.xml' : 'feed.php'); // RSS URL
	
	$smarty->assign('notice',      get_articles_cat_name('公告',3)); // 分类树

	$smarty->assign('news',      get_articles_cat_name('新闻',3)); // 分类树
	
    $smarty->assign('categories',      get_categories_tree_pro()); // 分类树
    $smarty->assign('helps',           get_shop_help());       // 网店帮助
    $smarty->assign('top_goods',       get_top10());           // 销售排行
	
//     $smarty->assign('best_goods',      get_recommend_goods('best'));    // 推荐商品
//     $smarty->assign('new_goods',       get_recommend_goods('new'));     // 最新商品
//     $smarty->assign('hot_goods',       get_recommend_goods('hot'));     // 最热商品
	$smarty->assign('my_comments',      every_buy_comments(12));    // 大家都在买

    $smarty->assign('promotion_goods', get_promote_goods()); // 特价商品
	
	$smarty->assign('promotion_goods_next', get_promote_goods_next()); // 下一期特价商品

	$smarty->assign('second_list',get_promote_second());//秒杀抢购
    $smarty->assign('brand_list',      get_brands());
	
	$smarty->assign('brand_list_index',      get_brands_index());
	$smarty->assign('group_buy_list_index',      group_buy_list_index());

    $smarty->assign('promotion_info',  get_promotion_info()); // 增加一个动态显示所有促销信息的标签栏

    $smarty->assign('invoice_list',    index_get_invoice_query());  // 发货查询
		
//     $smarty->assign('group_buy_goods', index_get_group_buy());      // 团购商品
//     $smarty->assign('auction_list',    index_get_auction());        // 拍卖活动
    $smarty->assign('shop_notice',     $_CFG['shop_notice']);       // 商店公告
	$smarty->assign('cfg', $_CFG);
	$smarty->assign('script_name', 'index');

	for($i=1;$i<=$_CFG['cat_ad'];$i++)
	{
		$ad_arr .= "'c".$i.",";
	}

	$smarty->assign('adarr',       $ad_arr); // 分类广告位

    /* 首页主广告设置 */
    $smarty->assign('index_ad',     $_CFG['index_ad']);
    if ($_CFG['index_ad'] == 'cus')
    {
        $sql = 'SELECT ad_type, content, url FROM ' . $ecs->table("ad_custom") . ' WHERE ad_status = 1';
        $ad = $db->getRow($sql, true);
        $smarty->assign('ad', $ad);
    }

   
    $smarty->assign('data_dir',        DATA_DIR);       // 数据目录

    /* 首页推荐分类 */
    $cat_recommend_res = $db->getAll("SELECT c.cat_id, c.cat_name, cr.recommend_type FROM " . $ecs->table("cat_recommend") . " AS cr INNER JOIN " . $ecs->table("category") . " AS c ON cr.cat_id=c.cat_id");
    if (!empty($cat_recommend_res))
    {
        $cat_rec_array = array();
        foreach($cat_recommend_res as $cat_recommend_data)
        {
            $cat_rec[$cat_recommend_data['recommend_type']][] = array('cat_id' => $cat_recommend_data['cat_id'], 'cat_name' => $cat_recommend_data['cat_name']);
        }
        $smarty->assign('cat_rec', $cat_rec);
    }

    /* 页面中的动态内容 */
    assign_dynamic('index');
    
    /* xie0127 lunbo */
    $time = gmtime();
    $sql = "SELECT a.*,ap.ad_width,ap.ad_height FROM ".$ecs->table('ad')." AS a ".
    		"LEFT JOIN ".$ecs->table('ad_position')." AS ap ON a.position_id=ap.position_id ".
    		"WHERE a.enabled = 1 AND a.start_time <= '$time' AND a.end_time >= '$time' AND ap.position_name='首页轮播' ".
    		"ORDER BY a.ad_id";
    $lunbo = $db->getAll($sql);
    
    $sql = "SELECT a.*,ap.ad_width,ap.ad_height FROM ".$ecs->table('ad')." AS a ".
    		"LEFT JOIN ".$ecs->table('ad_position')." AS ap ON a.position_id=ap.position_id ".
    		"WHERE a.enabled = 1 AND a.start_time <= '$time' AND a.end_time >= '$time' AND ap.position_name='首页轮播背景' ".
    		"ORDER BY a.ad_id";
    $lunboBack = $db->getAll($sql);
    
    foreach ($lunbo AS $k=>$row)
    {
    	switch ($row['media_type'])
    	{
    		case 0: // 图片广告
    			$src = (strpos($row['ad_code'], 'http://') === false && strpos($row['ad_code'], 'https://') === false) ?
    			DATA_DIR . "/afficheimg/$row[ad_code]" : $row['ad_code'];
    			$srcBack = (strpos($lunboBack[$k]['ad_code'], 'http://') === false && strpos($row['ad_code'], 'https://') === false) ?
    			DATA_DIR . "/afficheimg/".$lunboBack[$k]['ad_code']: $lunboBack[$k]['ad_code'];
    			$target = ($row["ad_link"]=='#'||$row["ad_link"]=='')?'':' target="_blank"';
    			$href = ($row["ad_link"]=='#'||$row["ad_link"]=='')?"javascript:void(0);":"affiche.php?ad_id=$row[ad_id]&amp;uri=" .urlencode($row["ad_link"]);
    			$lunbo[$k]['li'] = '<li style="background: transparent url('.$srcBack.') no-repeat scroll 50% 0px;
    			position: absolute; width: 4497px; left: 0px; top: 0px; display: list-item; opacity: 1;"><div class="b_width">
    			<a '.$target.' href="'.$href.'">
    			<img src="'.$src.'" height="450" width="1200"></a></div></li>';
    			break;
    		case 1: // Flash
    			$src = (strpos($row['ad_code'], 'http://') === false && strpos($row['ad_code'], 'https://') === false) ?
    			DATA_DIR . "/afficheimg/$row[ad_code]" : $row['ad_code'];
    			$lunbo[$k]['url'] = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" " .
    					"codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\"  " .
    					"width='$row[ad_width]' height='$row[ad_height]'>
    					<param name='movie' value='$src'>
    					<param name='quality' value='high'>
    					<embed src='$src' quality='high'
    					pluginspage='http://www.macromedia.com/go/getflashplayer'
    					type='application/x-shockwave-flash' width='$row[ad_width]'
    					height='$row[ad_height]'></embed>
    					</object>";
    			break;
    		case 2: // CODE
    			$lunbo[$k]['url'] = $row['ad_code'];
    			break;
    		case 3: // TEXT
    			$lunbo[$k]['url'] = "<a href='affiche.php?ad_id=$row[ad_id]&amp;uri=" .urlencode($row["ad_link"]). "'
                target='_blank'>" .htmlspecialchars($row['ad_code']). '</a>';
    			break;
    	}
    }
    
//     print_r($lunbo);
    $smarty->assign('lunbo',$lunbo);
    
    /* 优惠券  */
    $sql = 'SELECT bt.type_name,bt.img,bt.type_id,bt.limit_number,COUNT(ub.bonus_id) AS get_number FROM '.$ecs->table('bonus_type').' AS bt '.
      		'LEFT JOIN '.$ecs->table('user_bonus').' AS ub ON ub.bonus_type_id = bt.type_id '.
    		'WHERE bt.promotion_type = 1 AND bt.get_start_date <= '.$time.' AND bt.get_end_date >= '.$time.
    		' GROUP BY bt.type_id HAVING get_number < limit_number';
    $bonus = $db->getAll($sql);
    foreach ($bonus as $key=>$v){
    	$bonus[$key]['url'] = 'bonus.php?act=get&amp;id='.$v['type_id'];
    }
    $bonus_num = count($bonus);
    $bonus_width = ceil($bonus_num/2)*155;
//     print_r($bonus);
    $smarty->assign('bonus_width',$bonus_width);
    $smarty->assign('bonus',$bonus);
}

$smarty->display('index.dwt', $cache_id);

/*------------------------------------------------------ */
//-- PRIVATE FUNCTIONS
/*------------------------------------------------------ */

/**
 * 调用发货单查询
 *
 * @access  private
 * @return  array
 */
function index_get_invoice_query()
{
    $sql = 'SELECT o.order_sn, o.invoice_no, s.shipping_code FROM ' . $GLOBALS['ecs']->table('order_info') . ' AS o' .
            ' LEFT JOIN ' . $GLOBALS['ecs']->table('shipping') . ' AS s ON s.shipping_id = o.shipping_id' .
            " WHERE invoice_no > '' AND shipping_status = " . SS_SHIPPED .
            ' ORDER BY shipping_time DESC LIMIT 10';
    $all = $GLOBALS['db']->getAll($sql);

    foreach ($all AS $key => $row)
    {
        $plugin = ROOT_PATH . 'includes/modules/shipping/' . $row['shipping_code'] . '.php';

        if (file_exists($plugin))
        {
            include_once($plugin);

            $shipping = new $row['shipping_code'];
            $all[$key]['invoice_no'] = $shipping->query((string)$row['invoice_no']);
        }
    }

    clearstatcache();

    return $all;
}

/**
 * 获得最新的文章列表。
 *
 * @access  private
 * @return  array
 */
function index_get_new_articles($cat_id)
{
    $sql = 'SELECT a.article_id, a.title, ac.cat_name, a.add_time, a.file_url, a.open_type, ac.cat_id, ac.cat_name ' .
            ' FROM ' . $GLOBALS['ecs']->table('article') . ' AS a, ' .
                $GLOBALS['ecs']->table('article_cat') . ' AS ac' .
            ' WHERE a.is_open = 1 AND a.cat_id = ac.cat_id AND ac.cat_type = 1 AND ac.cat_id=' .$cat_id.
            ' ORDER BY a.article_type DESC, a.add_time DESC LIMIT ' . $GLOBALS['_CFG']['article_number'];
    $res = $GLOBALS['db']->getAll($sql);

    $arr = array();
    foreach ($res AS $idx => $row)
    {
        $arr[$idx]['id']          = $row['article_id'];
        $arr[$idx]['title']       = $row['title'];
        $arr[$idx]['short_title'] = $GLOBALS['_CFG']['article_title_length'] > 0 ?
                                        sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
        $arr[$idx]['cat_name']    = $row['cat_name'];
        $arr[$idx]['add_time']    = local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $arr[$idx]['url']         = $row['open_type'] != 1 ?
                                        build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']);
        $arr[$idx]['cat_url']     = build_uri('article_cat', array('acid' => $row['cat_id']), $row['cat_name']);
    }

    return $arr;
}

/**
 * 获得最新的团购活动
 *
 * @access  private
 * @return  array
 */
function index_get_group_buy()
{
    $time = gmtime();
    $limit = get_library_number('group_buy', 'index');

    $group_buy_list = array();
    if ($limit > 0)
    {
        $sql = 'SELECT gb.act_id AS group_buy_id, gb.goods_id, gb.ext_info, gb.goods_name, g.goods_thumb, g.goods_img ' .
                'FROM ' . $GLOBALS['ecs']->table('goods_activity') . ' AS gb, ' .
                    $GLOBALS['ecs']->table('goods') . ' AS g ' .
                "WHERE gb.act_type = '" . GAT_GROUP_BUY . "' " .
                "AND g.goods_id = gb.goods_id " .
                "AND gb.start_time <= '" . $time . "' " .
                "AND gb.end_time >= '" . $time . "' " .
                "AND g.is_delete = 0 " .
                "ORDER BY gb.act_id DESC " .
                "LIMIT $limit" ;
        $res = $GLOBALS['db']->query($sql);

        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            /* 如果缩略图为空，使用默认图片 */
            $row['goods_img'] = get_image_path($row['goods_id'], $row['goods_img']);
            $row['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);

            /* 根据价格阶梯，计算最低价 */
            $ext_info = unserialize($row['ext_info']);
            $price_ladder = $ext_info['price_ladder'];
            if (!is_array($price_ladder) || empty($price_ladder))
            {
                $row['last_price'] = price_format(0);
            }
            else
            {
                foreach ($price_ladder AS $amount_price)
                {
                    $price_ladder[$amount_price['amount']] = $amount_price['price'];
                }
            }
            ksort($price_ladder);
            $row['last_price'] = price_format(end($price_ladder));
            $row['url'] = build_uri('group_buy', array('gbid' => $row['group_buy_id']));
            $row['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
                                           sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
            $row['short_style_name']   = add_style($row['short_name'],'');
            $group_buy_list[] = $row;
        }
    }

    return $group_buy_list;
}

/**
 * 取得拍卖活动列表
 * @return  array
 */
function index_get_auction()
{
    $now = gmtime();
    $limit = get_library_number('auction', 'index');
    $sql = "SELECT a.act_id, a.goods_id, a.goods_name, a.ext_info, g.goods_thumb ".
            "FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS a," .
                      $GLOBALS['ecs']->table('goods') . " AS g" .
            " WHERE a.goods_id = g.goods_id" .
            " AND a.act_type = '" . GAT_AUCTION . "'" .
            " AND a.is_finished = 0" .
            " AND a.start_time <= '$now'" .
            " AND a.end_time >= '$now'" .
            " AND g.is_delete = 0" .
            " ORDER BY a.start_time DESC" .
            " LIMIT $limit";
    $res = $GLOBALS['db']->query($sql);

    $list = array();
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $ext_info = unserialize($row['ext_info']);
        $arr = array_merge($row, $ext_info);
        $arr['formated_start_price'] = price_format($arr['start_price']);
        $arr['formated_end_price'] = price_format($arr['end_price']);
        $arr['thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr['url'] = build_uri('auction', array('auid' => $arr['act_id']));
        $arr['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ?
                                           sub_str($arr['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $arr['goods_name'];
        $arr['short_style_name']   = add_style($arr['short_name'],'');
        $list[] = $arr;
    }

    return $list;
}



function group_buy_list_index()
{
    /* 取得团购活动 */
    $gb_list = array();
    $now = gmtime();
    $sql = "SELECT b.*, IFNULL(g.goods_thumb, '') AS goods_thumb, b.act_id AS group_buy_id, ".
                "b.start_time AS start_date, b.end_time AS end_date,g.shop_price " .
            "FROM " . $GLOBALS['ecs']->table('goods_activity') . " AS b " .
                "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON b.goods_id = g.goods_id " .
            "WHERE b.act_type = '" . GAT_GROUP_BUY . "' " .
            "AND b.start_time <= '$now' AND b.is_finished < 3 ORDER BY b.act_id DESC LIMIT 1";
	$res = $GLOBALS['db']->getAll($sql);

    foreach ($res as $group_buy)
    {
        $ext_info = unserialize($group_buy['ext_info']);
        $group_buy = array_merge($group_buy, $ext_info);
 		$group_buy['cur_amount'] = group_buy_stat($group_buy['act_id'], $group_buy['deposit']);
        /* 格式化时间 */
        $group_buy['formated_start_date']   = local_date($GLOBALS['_CFG']['time_format'], $group_buy['start_date']);
        $group_buy['formated_end_date']     = local_date($GLOBALS['_CFG']['time_format'], $group_buy['end_date']);
		
        /* 格式化保证金 */
        $group_buy['formated_deposit'] = price_format($group_buy['deposit'], false);

        /* 处理价格阶梯 */
        $price_ladder = $group_buy['price_ladder'];
        if (!is_array($price_ladder) || empty($price_ladder))
        {
            $price_ladder = array(array('amount' => 0, 'price' => 0));
        }
        else
        {
            foreach ($price_ladder as $key => $amount_price)
            {
                $price_ladder[$key]['formated_price'] = price_format($amount_price['price']);
            }
        }
        $group_buy['price_ladder'] = $price_ladder;

        /* 处理图片 */
        if (empty($group_buy['goods_thumb']))
        {
            $group_buy['goods_thumb'] = get_image_path($group_buy['goods_id'], $group_buy['goods_thumb'], true);
        }
        /* 处理链接 */
        $group_buy['url'] = build_uri('group_buy', array('gbid'=>$group_buy['group_buy_id']));
        /* 加入数组 */
    }

    return $group_buy;
}

?>